import { forwardRef } from 'react';
import { Form, Button, Space, Input, InputNumber, Select, DatePicker, Switch, Checkbox, Radio, Button } from 'antd'
import { useNavigate } from 'react-router-dom';

const { TextArea } = Input;

const controlMap = {
  input: (props) => <Input {...props} />,
  textarea: (props) => <TextArea {...props} />,
  number: (props) => <InputNumber style={{ width: '100%' }} {...props} />,
  select: (props, options = []) => (
    <Select {...props}>
      {Array.isArray(options) && options.map((op) => <Option key={op.value} value={op.value}>{op.label}</Option>)}
    </Select>
  ),
  date: (props) => <DatePicker style={{ width: '100%' }} {...props} />,
  switch: (props) => <Switch {...props} />,
  checkbox: (props, options = []) => (
    <Checkbox.Group options={options.map(o => ({ label: o.label, value: o.value }))} {...props} />
  ),
  radio: (props, options = []) => (
    <Radio.Group {...props}>
      {Array.isArray(options) && options.map(op => <Radio key={op.value} value={op.value}>{op.label}</Radio>)}
    </Radio.Group>
  )
}

const MAddPage = forwardRef((props, ref) => {
  const {
    schema = [],
    showSubmit = true,
    submitText = '保存',
    cancelText = '取消',
    layout = 'vertical',
    onFinish,
    formProps = {}
  } = props;
  const navigate = useNavigate();

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [form] = externalForm ? [externalForm] : Form.useForm();

  const renderField = (field) => {
    // todo 处理表单控件
  }

  return (
    <Form
      form={form}
      layout={layout}
      ref={ref}
      onFinish={onFinish}
      {...formProps}
      >
      {/* 渲染表单控件 */}
      {schema.map((field) => {
        const { name, label, rules = [], hidden = false, colProps = {} } = field
        if (hidden) return null
        return (
          <Form.Item key={name} name={name} label={label} rules={rules} {...colProps}>
            {renderField(field)}
          </Form.Item>
        )
      })}
      {/* 渲染操作按钮 */}
      {showSubmit &&
      <Form.Item>
        <Space>
          <Button type='primary' onClick={() => form.submit()}>{submitText}</Button>
          <Button type='default' onClick={() => navigate(-1)}>{cancelText}</Button>
        </Space>
      </Form.Item>}
    </Form>

  )
})

export default MAddPage;